package config;

import java.util.Properties;
import javax.sql.DataSource;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import tk.mybatis.spring.mapper.MapperScannerConfigurer;

/**
 * Project Name: ms
 * File Name: MsMybatisConfig
 * Package Name: config
 * Date: 2018/5/15  17:03
 * Copyright (c) 2018, tianyul All Rights Reserved.
 */
public abstract class MsMybatisConfig {
    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactory sqlSessionFactoryBean(@Qualifier(value = "dataSource") DataSource dataSource) {
        try {
            ResourcePatternResolver resourcePatternResolver;
            resourcePatternResolver = new PathMatchingResourcePatternResolver();
            SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
            bean.setDataSource(dataSource);
            bean.setTypeAliasesPackage(getTypeAliasesPackage());
            if (null != getMapperLocations() && !"".equals(getMapperLocations())) {
                bean.setMapperLocations(resourcePatternResolver.getResources(getMapperLocations()));
            }
            Configuration configuration = new Configuration();
            configuration.setUseColumnLabel(true); // 使用列别名替换列名 select user as User
            configuration.setMapUnderscoreToCamelCase(true); // 自动使用驼峰命名属性映射字段 userId user_id
            bean.setConfiguration(configuration);
            bean.setFailFast(true);
            return bean.getObject();
        } catch (Exception e) {
            throw new RuntimeException("sqlSessionFactory of mybatis init fail!", e);
        }
    }
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setBasePackage(getBasePackage());
        Properties properties = new Properties();
//        properties.setProperty("value", "mappers=mapper.MsMapper");
        properties.setProperty("mappers", "mapper.MsMapper");
        mapperScannerConfigurer.setProperties(properties);
        return mapperScannerConfigurer;
    }
    protected abstract String getTypeAliasesPackage();
    protected abstract String getMapperLocations();
    protected abstract String getBasePackage();
}
